package com.example.aqarapp.view.fragment;

import static com.example.aqarapp.view.MainPageActivity.FAMILY_CHANGE;
import static com.example.aqarapp.view.MainPageActivity.curRoomName;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.aqarapp.entity.BaseDeviceInfo;
import com.example.aqarapp.entity.BulbInfo;
import com.example.aqarapp.entity.CurtainInfo;
import com.example.aqarapp.entity.DeviceInfo;
import com.example.aqarapp.entity.DeviceListItem;
import com.example.aqarapp.entity.OneBean;
import com.example.aqarapp.entity.SocketInfo;
import com.example.aqarapp.entity.TwoBean;
import com.example.aqarapp.view.CirclePgBar;
import com.example.aqarapp.view.HorizontalItemDecoration;
import com.example.aqarapp.view.OutletDialog;
import com.example.aqarapp.view.adapter.DeviceListDeivceItemAdapter;
import com.example.aqarapp.view.adapter.DeviceListRecyclerAdapter;
import com.example.aqarapp.view.adapter.ListPlaceRecyclerAdapter;

import com.example.aqarapp.view.dialog.BulbControlDialog;
import com.example.aqarapp.view.dialog.CurtainControlDialog;
import com.example.aqarapp.view.utils.MessageEvent;
import com.example.aqarapp.viewmodel.FamilyInfoViewModel;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import aqarapp.R;

public class DeviceListFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "DeviceListFragment";
    private ArrayList<String> placeDataList;
    private ArrayList<String> dataList;
    private DeviceListRecyclerAdapter mDeviceListAdapter;
    private RecyclerView mDevicelistPlaceRv;
    private RecyclerView mDeviceListRv;
    private ListPlaceRecyclerAdapter mListPlaceAdapter;
    private BulbControlDialog mBulbControlDialog;
    private ImageButton bulbCancelBtn;
    private CurtainControlDialog mCurtainControlDialog;
    private ImageButton curtainCancelBtn;
    private SmartRefreshLayout smartRefreshLayout;
    private RadioGroup deviceRadioGroup;
    private OutletDialog mOutletDialog;
    private Button startBtn;
    private ConstraintLayout v1;
    private ConstraintLayout v2;
    private ImageButton socketCancelBtn;

    private Button mTenBtn;
    private Button mThirtyBtn;
    private Button mSixtyBtn;
    private CirclePgBar mCirclePgBar;

    private Button mPauseTimerBtn;
    private Button mCancleTimerBtn;
    private FamilyInfoViewModel mFamilyInfoViewModel;
    private MutableLiveData<List<String>> mRoomNameInfoLiveData;
    private MutableLiveData<List<OneBean>>  mDeviceListItemLivewData;
    private DeviceListDeivceItemAdapter mDeviceItemAdapter;
    private RadioButton deviceTypeRb;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_device_list_refresh_block, null);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViewModel();
        initRoomView(); //初始化位置标题
        initDeviceListRecyclerView();//初始化设备列表
        initRefreshLayout();//初始化刷新布局
        initRadioButton();
        init();


    }

    private void initViewModel() {
        mFamilyInfoViewModel = new ViewModelProvider(requireActivity()).get(FamilyInfoViewModel.class);
        mRoomNameInfoLiveData = (MutableLiveData<List<String>>) mFamilyInfoViewModel.getRoomNameInfo();
        mDeviceListItemLivewData = (MutableLiveData<List<OneBean>>) mFamilyInfoViewModel.getDeviceListInfo();
        mRoomNameInfoLiveData.observe(getViewLifecycleOwner(), item -> {
            mListPlaceAdapter.setList(item); //更新横排room名称
            mListPlaceAdapter.addData(0,"全部");
        });
        mDeviceListItemLivewData.observe(getViewLifecycleOwner(), item -> {
//            List<DeviceListItem> list = new ArrayList<>();
//            list.add(item);
//            mDeviceListAdapter.setList(list); //更新对应room cardView
            mDeviceItemAdapter.setList(item);
        });
       // mDeviceListItemLivewData.setValue(mFamilyInfoViewModel.getAllDeviceListItem("全部"));
    }

    public void init() {
        mCirclePgBar = (CirclePgBar) getView().findViewById(R.id.circlebar);
        deviceTypeRb = getView().findViewById(R.id.show_all_device_rb);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBulbControlDialog != null) {
            mBulbControlDialog.dismiss();
        }
        if (mCurtainControlDialog != null) {
            mCurtainControlDialog.dismiss();
        }

    }

    private void initRefreshLayout() {
        smartRefreshLayout = getView().findViewById(R.id.list_refreshLayout);
        smartRefreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Toast.makeText(getActivity(), "我请求下拉刷新数据", Toast.LENGTH_LONG).show();


                refreshLayout.finishRefresh(1000);//TODO 这里指定2s结束,后续可能根据数据返回回调通知结束刷新动画
            }
        });
    }

    private void initRoomView() {
        mDevicelistPlaceRv = getView().findViewById(R.id.list_place_rv);
        mDevicelistPlaceRv.setHasFixedSize(true); //设置固定大小
        //TODO 这里的间隔距离需要确定
        HorizontalItemDecoration itemDecoration =
                new HorizontalItemDecoration(25, getContext());
        mDevicelistPlaceRv.addItemDecoration(itemDecoration);
        //创建线性布局
        mListPlaceAdapter = new ListPlaceRecyclerAdapter(R.layout.layout_device_list_place_tab); //初始化适配器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false);
        mDevicelistPlaceRv.setLayoutManager(linearLayoutManager);
        mDevicelistPlaceRv.setAdapter(mListPlaceAdapter);
        mListPlaceAdapter.setEmptyView(R.layout.layout_empty);    //设置未发现设备时的布局
        mListPlaceAdapter.setOnItemClickListener(new OnItemClickListener() {  //卡片的点击事件
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //todo 选择快捷或其他地点需要显示对应的卡片页面
                Toast.makeText(getActivity(), "你点击了place" + (position + 1), Toast.LENGTH_SHORT).show();
                mListPlaceAdapter.setSelection(position);
                curRoomName = (String) adapter.getItem(position);
               mDeviceListItemLivewData.setValue( mFamilyInfoViewModel.getAllDeviceListItem(curRoomName));
               deviceTypeRb.setChecked(true);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(MessageEvent event) {
        switch (event.getMessage()) {
            case FAMILY_CHANGE:
                mListPlaceAdapter.setSelection(0);//当切换家庭时，房间重置为"全部"。
                deviceTypeRb.setChecked(true); //当切换家庭时，设备类型重置为“全部”。
                break;
        }
    }

    private void initDeviceListRecyclerView() {
        mDeviceListRv = getView().findViewById(R.id.device_list_recyclerview);
        mDeviceListRv.setHasFixedSize(true); //设置固定大小
//        mDeviceListAdapter = new DeviceListRecyclerAdapter(new ArrayList<>()); //初始化适配器
        mDeviceItemAdapter = new DeviceListDeivceItemAdapter(); //初始化适配器
        //mtestAdapter.setList( getEntity());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
        mDeviceListRv.setLayoutManager(linearLayoutManager);
//        mDeviceListRv.setAdapter(mDeviceListAdapter);
        mDeviceListRv.setAdapter(mDeviceItemAdapter);
        mDeviceItemAdapter.setEmptyView(R.layout.layout_empty);    //设置未发现设备时的布局
        mDeviceItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            public void onItemChildClick(@NonNull BaseQuickAdapter adpter, @NonNull View view, int position) {
                DeviceInfo deviceInfo = ((DeviceInfo) adpter.getItem(position));
                //不清楚为何setClickable = false 无效。
                if (deviceInfo.getState().equals("0")){
                    return;
                }
                String name = deviceInfo.getDeviceName();
                BaseDeviceInfo baseDeviceInfo = deviceInfo.getBaseDeviceInfo();
                adpter.getViewByPosition(position,R.id.test_device_list_info_view).setClickable(false);
                if (baseDeviceInfo instanceof BulbInfo) {
//                    Toast.makeText(getContext(), " BulbInfo Click "+name,Toast.LENGTH_SHORT).show();
                    showBulbInfDialog(deviceInfo, (BaseQuickAdapter<DeviceInfo, ?>) adpter, position);
                } else if (baseDeviceInfo instanceof SocketInfo) {
                    Toast.makeText(getContext(), " SocketInfo Click "+name,Toast.LENGTH_SHORT).show();
                    //TODO 暂未写相关dialog代码
//                    showOutletDialog(deviceInfo, (BaseQuickAdapter<DeviceInfo, ?>) adpter, position);
                } else if (baseDeviceInfo instanceof CurtainInfo) {
                    Toast.makeText(getContext(), " CurtainInfo Click "+name,Toast.LENGTH_SHORT).show();
                    showCurtainInfDialog(deviceInfo, (BaseQuickAdapter<DeviceInfo, ?>) adpter, position);
                }
            }
        });
//        mtestAdapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int i) {
//                switch (view.getId()){
//                    case R.id.test_device_list_info_iv:
//                        Toast.makeText(getContext(), " test2 Click !  ="+i, Toast.LENGTH_SHORT).show();
//                        break;
//                }
//
//            }
//        });
    }

    private void initRadioButton() {
        deviceRadioGroup = getView().findViewById(R.id.rg_device_type);
        deviceRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.show_all_device_rb:
                        //获取所有的设备
                        mDeviceListItemLivewData.setValue( mFamilyInfoViewModel.getAllDeviceListItem(curRoomName));
                        break;
                    case R.id.gateway_outage_rb:
                        //获取网管关闭的设备
                        mDeviceListItemLivewData.setValue( mFamilyInfoViewModel. getDeviceListGatewayItem(curRoomName));
                        break;
                    case R.id.socket_switch_rb:
                        //获取设备种类为插座的设备
                        mDeviceListItemLivewData.setValue( mFamilyInfoViewModel. getDeviceSpecifiedTypeItem(curRoomName,SocketInfo.class));
                        break;
                    case R.id.dimming_lighting_rb:
                        //获取设备种类为灯泡的设备
                        mDeviceListItemLivewData.setValue( mFamilyInfoViewModel. getDeviceSpecifiedTypeItem(curRoomName,BulbInfo.class));
                        break;
                    case R.id.door_window_shading_rb:
                        //获取设备种类为窗帘的设备
                        mDeviceListItemLivewData.setValue( mFamilyInfoViewModel. getDeviceSpecifiedTypeItem(curRoomName,CurtainInfo.class));
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void showBulbInfDialog(DeviceInfo deviceInfo, BaseQuickAdapter<DeviceInfo, ?> adapter, int position) {
        mBulbControlDialog = new BulbControlDialog(getContext(), deviceInfo, adapter, position);
        mBulbControlDialog.show();
        bulbCancelBtn = mBulbControlDialog.getWindow().findViewById(R.id.bulb_cancel_btn);
        bulbCancelBtn.setOnClickListener(this);

    }

    private void showCurtainInfDialog(DeviceInfo deviceInfo, BaseQuickAdapter<DeviceInfo, ?> adapter, int position) {
        mCurtainControlDialog = new CurtainControlDialog(getContext(), deviceInfo, adapter, position);
        mCurtainControlDialog.show();
        curtainCancelBtn = mCurtainControlDialog.getWindow().findViewById(R.id.curtain_cancel_btn);
        curtainCancelBtn.setOnClickListener(this);
    }
    private void showOutletDialog() {
        mOutletDialog = new OutletDialog(getContext());
        mOutletDialog.show();
        socketCancelBtn = mOutletDialog.getWindow().findViewById(R.id.socket_cancel_btn);
        socketCancelBtn.setOnClickListener(this);
        startBtn = mOutletDialog.getWindow().findViewById(R.id.start_btn);
        startBtn.setOnClickListener(this);
        mTenBtn = mOutletDialog.getWindow().findViewById(R.id.ten_btn);
        mTenBtn.setOnClickListener(this);
        mThirtyBtn = mOutletDialog.getWindow().findViewById(R.id.thirty_btn);
        mThirtyBtn.setOnClickListener(this);
        mSixtyBtn = mOutletDialog.getWindow().findViewById(R.id.sixty_btn);
        mSixtyBtn.setOnClickListener(this);
        v1 = mOutletDialog.getWindow().findViewById(R.id.settime);
        v2 = mOutletDialog.getWindow().findViewById(R.id.circle_timer);
        mCirclePgBar = (CirclePgBar) mOutletDialog.getWindow().findViewById(R.id.circlebar);
        mPauseTimerBtn = (Button) mOutletDialog.getWindow().findViewById(R.id.pause_btn);
        mPauseTimerBtn.setOnClickListener(this);
        mCancleTimerBtn = (Button) mOutletDialog.getWindow().findViewById(R.id.cancle_btn);
        mCancleTimerBtn.setOnClickListener(this);
    }

    //TODO 可以做一些网络数据刷新逻辑等。。。
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bulb_cancel_btn:
                mBulbControlDialog.hide();
                break;
            case R.id.curtain_cancel_btn:
                mCurtainControlDialog.hide();
                break;
            case R.id.socket_cancel_btn:
                mOutletDialog.hide();
                break;
            case R.id.start_btn:
                Log.d(TAG, "onClick: ");
                if (!mOutletDialog.getStartBtnEnabled()) {
                    Log.d(TAG, "onClick: dont click");
                }else {
                    int timeValue = mOutletDialog.getSetTimeValue();
                    mCirclePgBar.setMaxValue(timeValue);
                    mCirclePgBar.start();
                    v2.setVisibility(View.VISIBLE);
                    v1.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.ten_btn:
                mOutletDialog.setHour(0);
                mOutletDialog.setMinute(10);
                break;
            case R.id.thirty_btn:
                mOutletDialog.setHour(0);
                mOutletDialog.setMinute(30);
                break;
            case R.id.sixty_btn:
                mOutletDialog.setHour(1);
                mOutletDialog.setMinute(0);
                break;
            case R.id.pause_btn:
                CharSequence text = mPauseTimerBtn.getText();
                if(text.equals("暂停")) {
                    mPauseTimerBtn.setText("开始");
                    mCirclePgBar.pause(true);
                }
                else {
                    mPauseTimerBtn.setText("暂停");
                    mCirclePgBar.pause(false);
                }
                break;
            case R.id.cancle_btn:
                mCirclePgBar.stop();
                mPauseTimerBtn.setText("暂停");
                v2.setVisibility(View.INVISIBLE);
                v1.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }


    private List<BaseNode> getEntity() {
        //总的 list，里面放的是 FirstNode
        List<BaseNode> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {

            //SecondNode 的 list
            List<BaseNode> secondNodeList = new ArrayList<>();
            for (int n = 0; n <= 5; n++) {
                TwoBean seNode = new TwoBean("Second Node " + n);
                secondNodeList.add(seNode);
            }
            OneBean entity = new OneBean(secondNodeList, "First Node " + i);
            list.add(entity);
        }
        return list;
    }

}
